package com.example.zhu95.mytimber.utils

import com.example.zhu95.mytimber.MyApplication
import com.example.zhu95.mytimber.R
import com.example.zhu95.mytimber.entity.PlayListBean
import com.example.zhu95.mytimber.entity.SongBean
import com.example.zhu95.mytimber.entity.SongData
import com.example.zhu95.mytimber.entity.SongPlayCount
import org.litepal.crud.DataSupport
import java.util.*

/**
 * @author  zhu95
 * @date 2018/3/30 16:04
 */
object PlaylistUtils {

    private var SECOND: Long = 30 * 24 * 60 * 60
    private val CURRENT_TIME = System.currentTimeMillis() / 1000
    /**
     * 最新添加（播放列表）统计的是最近一段时间(这里默认设置为30天)内添加到本机的内容提供器的歌曲且列表
     */
    private fun initRecentAddList(): PlayListBean {
        val sharedPreferencesUtil = SharedPreferencesUtil.getSharedPreferencesUtil()
        val second = sharedPreferencesUtil.getLong(SharedPreferencesUtil.RECORD_SECOND)
        if (second == -1L) {
            sharedPreferencesUtil.put(SharedPreferencesUtil.RECORD_SECOND, SECOND)
        } else {
            SECOND = second
        }

        val recentPlaylist = PlayListBean()
        val songRecentList = ArrayList<SongBean>();
        for (song in SongData.songs) {
            if (song.addTime + SECOND >= CURRENT_TIME) {
                songRecentList.add(song)
            }
        }
        if (songRecentList.size > 0) {
            songRecentList.sortByDescending { it.addTime }
            val songIds = Util.getIdsStrFormat(songRecentList)
            recentPlaylist.songIds = songIds
        }
        recentPlaylist.title = MyApplication.getContext().resources.getString(R.string.recent_add)
        recentPlaylist.isDefaultList = true

        return recentPlaylist
    }

    //获取最近添加的歌曲，将记录的时间设置为在这之后
    fun clearRecentAddList() {
        var recentTime = -1L
        for (song in SongData.songs) {
            if (song.addTime > recentTime) {
                recentTime = song.addTime
            }
        }
        SECOND = CURRENT_TIME - recentTime - 1
        SharedPreferencesUtil.getSharedPreferencesUtil()
                .put(SharedPreferencesUtil.RECORD_SECOND, SECOND)
    }

    /**
     * 获取最近播放列表
     */
    private fun initRecentPlayList(): PlayListBean {
        val lists = DataSupport.select()
                .where("isdefaultlist=?", "1")
                .find(PlayListBean::class.java)
        var recentPlaylist: PlayListBean? = null
        try {
            recentPlaylist = lists[0]
        } catch (e: Exception) {
            e.printStackTrace()
        }

        if (recentPlaylist == null) {
            recentPlaylist = PlayListBean()
            recentPlaylist.title = MyApplication.getContext().getString(R.string.recent_play)
            recentPlaylist.isDefaultList = true
            recentPlaylist.songIds = ""
        }
        return recentPlaylist
    }

    /**
     * 清除最近播放列表的数据
     */
    fun clearRecentPlayList() {
        val recentPlayList = initRecentPlayList()
        recentPlayList.songIds = ""
        recentPlayList.save()
    }

    /**
     * 获取我的最佳曲目
     */
    private fun initMyTopSongList(): PlayListBean {
        val myTopSong = PlayListBean(MyApplication.getContext().getString(R.string.top_track), "", true)
        val songPlayCounts = DataSupport.select("songid", "score")
                .order("score desc ")
                .find(SongPlayCount::class.java)
        if (songPlayCounts != null && songPlayCounts.size > 0) {
            val sb = StringBuilder("")
            for ((songid) in songPlayCounts) {
                sb.append(songid)
                        .append("$")
            }
            sb.deleteCharAt(sb.length - 1)
            myTopSong.songIds = sb.toString()
        }
        return myTopSong
    }

    fun clearMyTopSongList() {
        DataSupport.deleteAll(SongPlayCount::class.java)
    }

    /**
     * 获取用户添加的播放列表
     */
    fun getUserAddLists(): List<PlayListBean> {
        val userAddLists = DataSupport.select().where("isdefaultlist=?", "0").find(PlayListBean::class.java)
        return userAddLists
    }

    fun getAllPlaylistData(): List<PlayListBean> {
        val playlists = ArrayList<PlayListBean>()
        playlists.add(initRecentAddList())
        playlists.add(initRecentPlayList())
        playlists.add(initMyTopSongList())
        val userAddLists = getUserAddLists()
        if (userAddLists.isNotEmpty()) {
            for (userAddList in userAddLists) {
                playlists.add(userAddList)
            }
        }
        return playlists
    }

    fun findPlaylistByTitle(title: String): PlayListBean? {
        for (playlist in getAllPlaylistData()) {
            if (playlist.title == title) {
                return playlist
            }
        }
        return null
    }

    fun deletePlaylist(title: String) {
        getUserAddLists().find { it.title == title }?.delete()
        /*   for (userAddList in getUserAddLists()) {
               if (userAddList.title == title) {
                   userAddList.deleteSong()
               }
           }*/
    }

    fun createPlaylist(playlistName: String): Boolean {
        val allPlaylistData = getAllPlaylistData()
        val listName = ArrayList<String>()
        for ((title) in allPlaylistData) {
            listName.add(title)
        }
        if (!listName.contains(playlistName)) {
            val playList = PlayListBean()
            playList.title = playlistName
            playList.isDefaultList = false
            playList.save()
            return true
        }
        return false
    }

    fun addSong2Playlist(songid: Int, playlistTitle: String): Boolean {
        val playlist = findPlaylistByTitle(playlistTitle)
        if (playlist == null) {
            return false
        }
        var songIds = playlist.songIds
        if (songIds.isNotEmpty()) {
            songIds += ("$$songid")
        } else {
            songIds = songid.toString()
        }
        playlist.songIds = songIds
        playlist.save()
        return true
    }

}